<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Admin\Leave;

class LeaveController extends Controller
{
    //
    public function index()
    {
        $data = Leave::where('pid', '=', 0) -> get();
       
        return view('admin.leave.index', compact('data'));

    }
    public function show(Request $request)
    {


        $id = $request -> get('id');
        $table = new Leave();

        // 1.查找儿子大于一个的数据
        //$data = Leave::has('child', '>=', 1)->get();
        //dd($data);

        // 2.$data = Leave::whereHas('child', function ($query) {
            // 查找的是儿子的数据过滤其中的数据
            //$query->where('pid', '0');
        //})->get();

        // 3.$data = Leave::where('id', $id)->withCount('child')->get();
        //dd($data->toArray());//数一下有几个儿子

        //Leave::where('id', $id)->with('allChild') -> first() 取出所有的相关数据 递归取出所有的层级
        //$data = Leave::where('id', $id)->with('allChild') -> first(); //1
        //$data = Leave::where('id', $id)->with('allChild') -> first()->allChild;  //2 
        //$data = Leave::where('id', $id)->with('allChild') -> first()->allChild->first(); //3
        //$data = Leave::where('id', $id)->with('allChild') -> first()->allChild->first()->allChild; //4

        // 4. 完美取出所有的数据 可以尝试反向定义 依据 pid找到id 找父级元素 with是预加载的意思
        // foreach ($data as $key => $value) {
        //     dd($value->comment);
        // }
        // dd($data->toArray());
        // dd($data->comment);
        //dd($data->toArray());

        $datas = Leave::all();//取出所有的数据
        $leave = $table->fen($datas);
        //         $data =[];
        //         foreach ($leave as $key => $value) {
        //             $data[] = $value->toArray();
        //         }
        //         dd($data);
        //         dd($leave);

        //  dd($leave);
        return view('admin.leave.show', compact('leave'));
    }

    public function modify(Request $request)
    {
        $id = $request -> get('id');
        $status = Leave::where('id', '=', $id) -> value('status');
        //var_dump($status);
        if ($status == '1') {
            $result = Leave::where('id', '=', $id)->update(['status' => '2']);
        } else {
            $result =  Leave::where('id', '=', $id)->update(['status' => '1']);
            
        }
        if ($result == 1) {
            return response()->json(
                [
                'info' => '1'
                ]
            );
        } else {
            return response()->json(
                [
                'info' => '2',
                'error' => '修改失败'
                ]
            );
        }
        
    }
}
